import { keys } from "@/utils/storage/keys";

export const useMenus = defineStore(
  "menu",
  () => {
    const menus = ref([]);
    // 异步返回的权限路由
    const rightList = ref([]);
    // 面包屑导航栏
    const breadItemList: any = ref([]);

    // 设置面包屑数据
    const setBreadItem = (list: any) => {
      breadItemList.value = list;
    };
    // 本地存储权限
    const setRightsData = (rights: any) => {
      // 权限值
      rightList.value = rights;
    };
    /**
     * 设置路由信息
     * @param rights 用户权限值
     * @param asyncRoutes 参与异步更新的路由
     * @param fixedRoutes 固定路由
     *  */
    const setMenus = (asyncRoutes: any, fixedRoutes: any) => {
      // 根据权限 返回的动态路由
      let rightsRoutes = [];
      if (asyncRoutes && asyncRoutes.length > 0) {
        rightsRoutes = getFilterRoutes(asyncRoutes, rightList.value);
      }
      // 导航栏显示
      menus.value = getFilterMenus([...fixedRoutes, ...rightsRoutes], "");
    };
    // 处理需要显示的导航
    const getFilterMenus = (arr: any, parentPath = "") => {
      const menus: any = [];
      arr.forEach((item: any) => {
        if (!item.meta.hidden) {
          const menu: any = {
            url: generateUrl(item.path, parentPath),
            title: item.meta.title,
            icon: item.meta.icon,
            activeMenu: item.meta.activeMenu,
            count: 0,
            menuLevel: item.menuLevel,
          };
          if (
            item.children &&
            item.children.filter((child: any) => !child.hidden).length > 0
          ) {
            menu.children = getFilterMenus(item.children, menu.url);
          }
          menus.push(menu);
        }
      });

      return menus;
    };
    // 权限处理
    const getFilterRoutes = (targetRoutes: any, ajaxRoutes: any) => {
      const filterRoutes: any = [];
      ajaxRoutes.forEach((item: any) => {
        const target = targetRoutes.find(
          (route: any) => route.meta.role === item.value
        );

        if (target) {
          const { children: targetChildren, ...rest } = target;
          const route = {
            ...rest,
          };
          if (targetChildren) {
            route.children = getFilterRoutes(targetChildren, ajaxRoutes);
          }
          if (route.meta && route.meta.title) {
            route.meta.title = item.name;
          }
          filterRoutes.push(route);
        }
      });
      return filterRoutes;
    };
    // 路由拼接
    const generateUrl = (path: string, parentPath: string) => {
      return path.startsWith("/")
        ? path
        : path
        ? `${parentPath}/${path}`
        : parentPath;
    };

    return {
      menus,
      rightList,
      breadItemList,
      setRightsData,
      setMenus,
      setBreadItem,
    };
  },
  {
    persist: {
      key: keys.menus,
      storage: localStorage,
    },
  }
);
